﻿<template>
    <div class="esProductChannelPlan-container">
        <el-dialog v-model="state.isShowDialog" draggable width="769px">
            <template #header>
                <div style="color: #fff">
                    <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
                        <ele-Edit/>
                    </el-icon>
                    <span> {{ props.title }} </span>
                </div>
            </template>
            <el-form :model="state.ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="产品渠道" prop="productChannelId">
                            <el-select v-model="state.selectProductChannel" filterable placeholder="请选择" class="w100"
                                       :disabled='props.title=="编辑"'>
                                <el-option v-for='item in state.productChannelDict' :key='item.value'
                                           :label='item.label' :value='item'/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管控级别" prop="controlLevel">
                            <el-input-number v-model="state.ruleForm.controlLevel" placeholder="请输入管控级别" :min="0"
                                             controls-position="right" class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="state.ruleForm.status" placeholder="请输入状态" class="w100">
                                <el-option label="启用" :value="1"></el-option>
                                <el-option label="停用" :value="2" :disabled="true"></el-option>
                                <el-option label="到量" :value="3"></el-option>
                                <el-option label="短期关停" :value="4"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label='日期'>
                            <el-date-picker class='w100' v-model='state.DateRange' type='datetimerange'
                                            range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
                                            date-format="YYYY/MM/DD" time-format="HH:mm:ss"
                                            value-format="YYYY-MM-DD HH:mm:ss"
                                            :default-time="defaultTime"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="起始时间" prop="dailyStartHour">
                            <el-select
                                v-model="state.ruleForm.dailyStartHour"
                                placeholder="请选择起始小时"
                                class="w100"
                                clearable
                                @change="handleStartHourChange"
                            >
                                <template #prefix>
                                    <i class="ele-Plus" style="margin-right: 8px;"></i>
                                </template>
                                <el-option
                                    v-for="hour in hours"
                                    :key="'start-' + hour"
                                    :label="formatStartHour(hour)"
                                    :value="hour"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="结束时间" prop="dailyEndHour">
                            <el-select
                                v-model="state.ruleForm.dailyEndHour"
                                placeholder="请选择结束小时"
                                class="w100"
                                clearable
                                :disabled="!state.ruleForm.dailyStartHour"
                                @change="handleEndHourChange"
                            >
                                <el-option
                                    v-for="hour in availableEndHours"
                                    :key="'end-' + hour"
                                    :label="formatEndHour(hour)"
                                    :value="hour"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="互斥周期" prop="phoneUniqueMonthly">
                            <el-input-number v-model="state.ruleForm.phoneUniqueMonthly" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入手机号业务互斥周期：月单位"
                                             class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="当日同步" prop="syncPlanDaily">
                            <el-radio-group v-model="state.ruleForm.syncPlanDaily" class="ml-4">
                                <el-radio
                                    v-for="item in optionDict.YesNoRawDict"
                                    :key="item.value"
                                    :label="item.value"
                                >
                                    {{ item.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
                        <el-form-item label="到量控制" prop="arrivalType">
                            <el-radio-group v-model="state.ruleForm.arrivalType">
                                <el-radio :label="1">请求</el-radio>
                                <el-radio :label="2">用户</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
                        <el-form-item label="请求上限" prop="requestLimit">
                            <el-input-number v-model="state.ruleForm.requestLimit" placeholder="请输入上限" :min="0"
                                             controls-position="right" class="w100"
                                             :disabled="state.ruleForm.arrivalType !== 1"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
                        <el-form-item label="用户上限" prop="userLimit">
                            <el-input-number v-model="state.ruleForm.userLimit" placeholder="请输入用户上限" :min="0"
                                             controls-position="right" class="w100"
                                             :disabled="state.ruleForm.arrivalType !== 2"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="备注">
                            <el-input v-model="state.ruleForm.remark" placeholder="请输入备注内容" clearable
                                      type="textarea"
                                      maxlength="255" :autosize="{ minRows: 2 }"/>
                        </el-form-item>
                    </el-col>
                    <el-divider border-style="dashed"/>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-button icon="ele-Plus" type="primary" plain @click="addExtOrgRow"> 增加省份与屏蔽城市
                        </el-button>
                        <el-button icon="ele-Plus" type="primary" plain @click="addNational"> 增加全国省份</el-button>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <template
                            v-if="state.ruleForm.provinceList != undefined && state.ruleForm.provinceList.length > 0">
                            <el-row :gutter="35" v-for="(v, k) in state.ruleForm.provinceList" :key="k">
                                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                    <el-form-item label="省份" prop="province" class="higlabel">
                                        <template #label>
                                            <el-button icon="ele-Delete" type="danger" circle plain size="small"
                                                       @click="deleteExtOrgRow(k)"/>
                                            <span class="ml5">省份</span>
                                        </template>
                                        <el-select v-model="state.ruleForm.provinceList[k].province" filterable
                                                   placeholder="省份"
                                                   class="w100">
                                            <el-option v-for='item in optionDict.provinceDict' :key='item.value'
                                                       :label='item.label' :value='item.value'/>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                    <el-form-item label="屏蔽城市" prop="screenCity">
                                        <el-input v-model="state.ruleForm.provinceList[k].screenCity"
                                                  placeholder="请输入屏蔽城市" clearable></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </template>
                        <el-empty :image-size="80" description="空数据" v-else></el-empty>
                    </el-col>

                </el-row>
            </el-form>
            <template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel" size="default">取 消</el-button>
					<el-button type="primary" @click="submit" size="default">确 定</el-button>
				</span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="editEsProductChannelPlan">

import {computed, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import type {FormRules} from "element-plus";
import mittBus from '/@/utils/mitt';
import {optionDict} from '/@/const/dict';
import {EsProductChannelPlan, sysBaseDict} from '/@/api/models';
import SysEsProductChannelPlanApi from '/@/api/exocytosis/productChannelPlan';
import SysEsProductChannelApi from '/@/api/exocytosis/productChannel';
import {getNowDates} from '/@/utils/formatTime';

const props = defineProps({
    title: String,
});

// 刚进入页面给的默认当前日期
const defaultDate = getNowDates();
// 设置默认时间
const defaultTime = ref([new Date(), new Date(0, 0, 0, 23, 59, 59)]);
// 生成0-23小时选项
const hours = Array.from({ length: 24 }, (_, i) => i);

const ruleFormRef = ref();
const state = reactive({
    DateRange: [],
    productChannelDict: [] as sysBaseDict[],
    selectProductChannel: null,
    isShowDialog: false,
    ruleForm: {} as EsProductChannelPlan,
});

// 删除非必填规则
const rules = ref<FormRules>({
    productChannelId: [{required: true, message: '请输入产品渠道ID！', trigger: 'blur',},],
});

// 打开弹窗
const openDialog = async (row: EsProductChannelPlan, conDition: string) => {
    await productChannelQuery();
    state.selectProductChannel = state.productChannelDict.find((item) => {
        return item.value === row.productChannelId;
    }) ?? null;
    if (conDition == 'add') {
        state.ruleForm = row;
        state.isShowDialog = true;
        state.ruleForm.provinceList = [{}];

        state.DateRange = defaultDate;

        // 到量控制有问题的话做这个操作
        if (state.ruleForm.arrivalType === 1) isArrival.isArrivalControl = true;
    } else {
        state.ruleForm = row;
        state.isShowDialog = true;
        state.ruleForm.provinceList = [{province: state.ruleForm.province, screenCity: state.ruleForm.screenCity}];
        state.DateRange = [row.startTime, row.endTime];

        // 到量控制有问题的话做这个操作
        isArrival.isArrivalControl = true;
        if (state.ruleForm.arrivalType === 2) isArrival.isArrivalControl = false;
    }
};

// 关闭弹窗
const closeDialog = () => {
    mittBus.emit('submitRefresh');
    state.isShowDialog = false;
    state.DateRange = [];
};

// 取消
const cancel = () => {
    state.isShowDialog = false;
};

// 提交
const submit = () => {
    if (state.ruleForm.arrivalType === 1)
        state.ruleForm.userLimit = 0;
    else
        state.ruleForm.requestLimit = 0;
    state.ruleForm.generateTodayPlan = state.ruleForm.generateTodayPlan == true ? 1 : 2;
    state.ruleForm.startTime = state.DateRange[0];
    state.ruleForm.endTime = state.DateRange[1];
    state.ruleForm.productChannelId = state.selectProductChannel?.value;
    state.ruleForm.productChannelCode = state.selectProductChannel?.exValue;
    ruleFormRef.value.validate(async (valid: boolean, fields?: any) => {
        if (valid) {
            let res;
            if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
                res = await SysEsProductChannelPlanApi().editPost(state.ruleForm);
            } else {
                res = await SysEsProductChannelPlanApi().addPost(state.ruleForm);
            }
            if (res.data.resCode != '0000')
                ElMessage.error(res.data.resMessage);
            else {
                ElMessage.success("操作成功");
                closeDialog();
            }
        } else {
            ElMessage({
                message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
                type: "error",
            });
        }
    });
};

// 增加附属机构行
const addExtOrgRow = () => {
    if (state.ruleForm.provinceList == undefined) state.ruleForm.provinceList = [];
    state.ruleForm.provinceList?.push({});
};

// 删除附属机构行
const deleteExtOrgRow = (k: number) => {
    if (state.ruleForm.provinceList.length == 1) {
        ElMessage({
            message: `最少选中一个省份`,
            type: "error",
        });
        return;
    }
    state.ruleForm.provinceList?.splice(k, 1);
};

// 产品渠道字典
const productChannelQuery = async () => {
    await SysEsProductChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.productChannelDict = res.data.result ?? [];
    });
};

// 增加全国省份
const addNational = () => {
    state.ruleForm.provinceList = []
    optionDict.provinceDict.map((item) => {
        state.ruleForm.provinceList?.push({
            province: item.value
        });
    })
}

// 时间处理
// 可选的结束小时（不能早于开始小时）
const availableEndHours = computed(() => {
    if (!state.ruleForm.dailyStartHour && state.ruleForm.dailyStartHour !== 0) {
        return hours;
    }
    return hours.filter(hour => hour >= state.ruleForm.dailyStartHour);
});

// 格式化显示
const formatStartHour = (hour) => {
    return `${String(hour).padStart(2, '0')}:00:00`;
};

const formatEndHour = (hour) => {
    return `${String(hour).padStart(2, '0')}:59:59`;
};

// 处理开始时间变化
const handleStartHourChange = (val) => {
    if (val === null) {
        state.ruleForm.dailyEndHour = 23;
    } else if (state.ruleForm.dailyEndHour !== null && state.ruleForm.dailyEndHour < val) {
        state.ruleForm.dailyEndHour = val;
        ElMessage.warning('结束时间已自动调整为不小于开始时间');
    }
};

// 处理结束时间变化
const handleEndHourChange = (selectedEndHour) => {
    if (selectedEndHour === null) {
        state.ruleForm.dailyEndHour = 23;
        return;
    }

    if (state.ruleForm.dailyStartHour !== null && selectedEndHour < state.ruleForm.dailyStartHour) {
        state.ruleForm.dailyEndHour = state.ruleForm.dailyStartHour;
        ElMessage.warning('结束时间不能早于开始时间，已自动调整');
    } else {
        state.ruleForm.dailyEndHour = selectedEndHour;
    }
};

// 导出对象 将属性或者函数暴露给父组件
defineExpose({openDialog});
</script>

<style lang="scss" scoped>
.higlabel {
    :deep(label) {
        display: flex;
        align-items: center;
    }
}
</style>
